// 自动注册路由
const koaRouter = require('koa-router')()
const fs = require('fs')
const dir = 'routes'
function registerRouter(router, mapping){
  for(let url in mapping){
    if(url.startsWith('GET ')){
       const qureyPath = url.substring(4)
       router.get(qureyPath, mapping[url])
    }else if(url.startsWith('POST ')){
        const qureyPath = url.substring(5)
       router.post(qureyPath, mapping[url])
    }else{
       console.log(`invalid URL: ${url}`)
    }
  }
}

function initRouter(){
    fs.readdirSync(dir)
    .filter((f) => f.endsWith('.js'))
    .forEach( (f)=>{
      const mapping = require(__dirname + '/' + dir + '/' + f)
      registerRouter(koaRouter, mapping)
    })
    return koaRouter.routes()
}
module.exports = initRouter